package com.doge.calcalbum.api

import android.content.Context
import androidx.lifecycle.LifecycleOwner
import com.doge.calcalbum.widgets.LoadingDialog
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

open class SimpleObserverAdapter<T>(private val context: Context, owner: LifecycleOwner) :
    ObserverAdapter<T>() {
    open val loadingDelay: Long = 800L
    private var displayTask: Disposable? = null
    private var loadingDialog: LoadingDialog? = null

    init {
        bindLifecycle(owner)
    }

    override fun onComplete() {
        release()
    }

    override fun onError(e: Throwable) {
        super.onError(e)
        release()
    }

    // also invoke when context onStop
    fun release() {
        displayTask?.dispose()
        loadingDialog?.dismiss()
        loadingDialog = null
    }

    override fun onStart() {
        displayTask = Observable.timer(loadingDelay, TimeUnit.MILLISECONDS)
            .subscribeOnIO()
            .observeOnMain()
            .doOnNext {
                loadingDialog = LoadingDialog.Builder(context).setCancelable(false).create()
                loadingDialog?.show()
            }
            .subscribe()
    }
}